<template>
  <div
    class="min-h-screen flex flex-col bg-gradient-to-br from-gray-50 to-gray-100 dark:from-gray-900 dark:to-gray-800 text-gray-800 dark:text-gray-100">
    <!-- 顶部导航 -->
    <header class="py-6 px-4 md:px-8 shadow-sm bg-white/80 dark:bg-gray-900/80 backdrop-blur-sm">
      <div class="max-w-6xl mx-auto">
        <h1 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold text-center text-indigo-600 dark:text-indigo-400">
          <i class="fas fa-camera-retro mr-2"></i>照片尺寸与背景处理工具
        </h1>
        <p class="text-center mt-2 text-gray-600 dark:text-gray-400">轻松调整一寸/两寸照片并修改背景颜色</p>
      </div>
    </header>

    <!-- 主内容区 - 使用flex-grow确保填充空间 -->
    <main class="flex-grow max-w-6xl w-full mx-auto px-4 py-6 md:py-10 overflow-hidden">
      <div class="h-full flex flex-col lg:flex-row gap-6">
        <!-- 左侧：上传与设置 - 自适应高度 -->
        <div
          class="bg-white dark:bg-gray-800 rounded-xl shadow-md p-6 flex-grow lg:flex-grow-0 lg:w-1/2 transform transition-all hover:shadow-lg overflow-auto max-h-[calc(100vh-12rem)]">
          <div class="w-full">
            <h2 class="text-xl font-semibold mb-6 flex items-center">
              <i class="fas fa-upload text-indigo-500 mr-2"></i>上传与设置
            </h2>

            <!-- 照片上传区域 -->
            <div
              class="border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg p-8 text-center mb-6 cursor-pointer hover:border-indigo-500 transition-colors"
              @click="triggerFileInput">
              <input type="file" ref="fileInput" accept="image/*" class="hidden" @change="handleFileUpload">
              <i class="fas fa-cloud-upload-alt text-4xl text-gray-400 mb-3"></i>
              <p class="text-gray-500 dark:text-gray-400">点击上传照片或拖放至此处</p>
              <p class="text-sm text-gray-400 dark:text-gray-500 mt-1">支持JPG、PNG等常见格式</p>
            </div>

            <!-- 背景颜色选择 -->
            <div class="mb-6">
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                <i class="fas fa-fill mr-1"></i>背景颜色
              </label>
              <div class="flex flex-wrap gap-3">
                <button v-for="color in backgroundColors" :key="color.value" :style="{ backgroundColor: color.value }"
                  class="w-8 h-8 rounded-full border-2 transition-transform hover:scale-110"
                  :class="selectedColor === color.value ? 'border-indigo-500 ring-2 ring-indigo-200' : 'border-transparent'"
                  @click="selectedColor = color.value" :title="color.name"></button>

                <input type="color" v-model="selectedColor" class="w-8 h-8 p-0 border-0 rounded-full cursor-pointer"
                  title="自定义颜色">
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="flex flex-col sm:flex-row gap-3 mt-8">
              <button
                class="flex-1 bg-indigo-600 hover:bg-indigo-700 text-white font-medium py-3 px-4 rounded-lg transition-all transform hover:scale-[1.02] active:scale-[0.98] flex items-center justify-center"
                @click="processImage" :disabled="!imageLoaded">
                <i class="fas fa-magic mr-2"></i>处理照片
              </button>
              <button
                class="flex-1 bg-green-600 hover:bg-green-700 text-white font-medium py-3 px-4 rounded-lg transition-all transform hover:scale-[1.02] active:scale-[0.98] flex items-center justify-center"
                @click="downloadImage" :disabled="!processedImage">
                <i class="fas fa-download mr-2"></i>下载照片
              </button>
            </div>
          </div>
        </div>

        <!-- 右侧：预览区域 - 自适应高度 -->
        <div
          class="bg-white dark:bg-gray-800 rounded-xl shadow-md p-6 flex-grow lg:flex-grow-0 lg:w-1/2 transform transition-all hover:shadow-lg overflow-auto max-h-[calc(100vh-12rem)]">
          <div class="w-full">
            <h2 class="text-xl font-semibold mb-6 flex items-center">
              <i class="fas fa-image text-indigo-500 mr-2"></i>预览
            </h2>

            <!-- 预览区域使用flex布局确保内容合理分布 -->
            <div class="flex flex-col h-full">
              <!-- 原始与处理后照片对比 -->
              <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6 flex-shrink-0">
                <!-- 原始照片 -->
                <div class="text-center">
                  <h3 class="text-sm font-medium text-gray-600 dark:text-gray-400 mb-3">原始照片</h3>
                  <div
                    class="bg-gray-100 dark:bg-gray-700 rounded-lg p-4 min-h-[180px] flex items-center justify-center overflow-hidden">
                    <div v-if="originalImage" class="relative">
                      <img :src="originalImage" alt="原始照片" class="max-w-full max-h-[180px] object-contain shadow-sm">
                    </div>
                    <div v-else class="text-gray-400">
                      <i class="fas fa-camera text-4xl mb-2 block"></i>
                      <p>未上传照片</p>
                    </div>
                  </div>
                </div>

                <!-- 处理后照片 -->
                <div class="text-center">
                  <h3 class="text-sm font-medium text-gray-600 dark:text-gray-400 mb-3">处理后照片</h3>
                  <div
                    class="bg-gray-100 dark:bg-gray-700 rounded-lg p-4 min-h-[180px] flex items-center justify-center overflow-hidden">
                    <div v-if="processedImage" class="relative">
                      <img :src="processedImage" alt="处理后照片" class="max-w-full max-h-[180px] object-contain shadow-sm">
                    </div>
                    <div v-else class="text-gray-400">
                      <i class="fas fa-image text-4xl mb-2 block"></i>
                      <p>未处理照片</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 页脚 - 固定在底部 -->
    <footer class="py-4 px-4 bg-white/80 dark:bg-gray-900/80 backdrop-blur-sm mt-auto">
      <div class="max-w-6xl mx-auto text-center text-gray-500 dark:text-gray-400 text-sm">
        <p>照片处理工具 &copy; {{ new Date().getFullYear() }} | 所有处理均在本地完成，不会上传您的照片</p>
      </div>
    </footer>

    <!-- 加载中提示 -->
    <div v-if="isProcessing" class="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50">
      <div class="bg-white dark:bg-gray-800 p-6 rounded-xl shadow-2xl text-center max-w-xs w-full">
        <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600 mx-auto mb-4"></div>
        <p class="text-gray-700 dark:text-gray-300">正在处理照片...</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, defineProps, onMounted } from 'vue';

const props = defineProps(['predict'])

// 图片状态
const originalImage = ref('');
const processedImage = ref('');
const imageLoaded = ref(false);
const isProcessing = ref(false);

// DOM引用
const fileInput = ref(null);
const previewCanvas = ref(null);



// 颜色设置
const selectedColor = ref('#ffffff'); // 默认白色背景
const backgroundColors = [
  { name: '白色', value: '#ffffff' },
  { name: '红色', value: '#ff0000' },
  { name: '蓝色', value: '#0066cc' },
  { name: '浅蓝色', value: '#add8e6' },
  { name: '灰色', value: '#808080' },
];

// 计算属性 - 根据选择的尺寸计算画布大小（像素）
const canvasWidth = computed(() => {
  // 按300dpi计算，1英寸=25.4毫米
  // 一寸: 25×35mm → 约295×413像素
  // 二寸: 35×49mm → 约413×579像素
  return selectedSize.value === '1x1' ? 295 : 413;
});

const canvasHeight = computed(() => {
  return selectedSize.value === '1x1' ? 413 : 579;
});

// 预览容器样式 - 确保不会超出父容器
const previewContainerStyle = computed(() => {
  return {
    maxWidth: '100%',
    maxHeight: 'calc(100% - 2rem)', // 留出底部文字空间
  };
});

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value.click();
};

// 处理文件上传
const handleFileUpload = (e) => {
  const file = e.target.files[0];
  if (!file) return;

  // 检查文件类型
  if (!file.type.startsWith('image/')) {
    alert('请上传图片文件');
    return;
  }

  // 读取图片
  const reader = new FileReader();
  reader.onload = (event) => {
    originalImage.value = event.target.result;
    imageLoaded.value = true;
    processedImage.value = ''; // 重置处理后的图片
  };
  reader.readAsDataURL(file);
};

// 处理图片
const processImage = async () => {
  if (!originalImage.value) return;

  isProcessing.value = true;

  try {
    // 传递尺寸参数（1x1表示一寸，2x2表示二寸）
    const canvas = await props.predict(originalImage.value, selectedColor.value);
    // 将canvas转换为图片并保存到processedImage变量
    console.log(canvas, 'canvas');

    processedImage.value = canvas.toDataURL('image/png');
  } catch (error) {
    console.error('图片处理错误:', error);
    alert('处理图片时发生错误，请重试');
  } finally {
    isProcessing.value = false;
  }
};


// 下载图片
const downloadImage = () => {
  if (!processedImage.value) return;

  const link = document.createElement('a');
  link.download = `processed-${selectedSize.value}-${new Date().getTime()}.png`;
  link.href = processedImage.value;
  link.click();
};

onMounted(() => {
  // 初始化画布尺寸
  /* const canvas = previewCanvas.value;
  canvas.width = canvasWidth.value;
  canvas.height = canvasHeight.value; */
});

</script>

<style scoped>
/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 深色模式滚动条 */
.dark ::-webkit-scrollbar-track {
  background: #333;
}

.dark ::-webkit-scrollbar-thumb {
  background: #555;
}

.dark ::-webkit-scrollbar-thumb:hover {
  background: #666;
}

/* 动画效果 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
